package com.kainitram.drivebook.data;

import java.sql.SQLException;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.kainitram.drivebook.R;
import com.kainitram.drivebook.models.Car;
import com.kainitram.drivebook.models.eFuelType;
import com.kainitram.morm.BaseDatabaseHelper;

/**
 * Database helper for drive book
 * 
 * @author Mino
 * 
 */
public class DatabaseHelper extends BaseDatabaseHelper {

	private static final String DATABASE_NAME = "drivebook.db";
	private static final int DATABASE_VERSION = 1;

	private Dao<Car, Integer> carDao;

	public DatabaseHelper(Context context) {
		super(context, DATABASE_NAME, DATABASE_VERSION, R.raw.ormlite_config);
	}

	@Override
	public void onCreate(SQLiteDatabase arg0, ConnectionSource connectionSource) {

		try {
			TableUtils.createTable(connectionSource, Car.class);

			createDefaultEntities();
		} catch (SQLException e) {
			Log.e(DatabaseHelper.class.getName(), "Unable to create datbases",
					e);
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase sqliteDatabase,
			ConnectionSource connectionSource, int oldVer, int newVer) {
		try {
			TableUtils.dropTable(connectionSource, Car.class, true);
			onCreate(sqliteDatabase, connectionSource);
		} catch (SQLException e) {
			Log.e(DatabaseHelper.class.getName(),
					"Unable to upgrade database from version " + oldVer
							+ " to new " + newVer, e);
		}
	}

	public Dao<Car, Integer> getCarDao() throws SQLException {
		if (carDao == null) {
			carDao = getDao(Car.class);
		}
		return carDao;
	}

	private void createDefaultEntities() {
		Car car = new Car();
		car.setEvc("AA 000 AA");
		car.setFuelType(eFuelType.NATURAL95);
		car.setTachometerState(10);
		car.setConsumptionCombine(5.5);
		car.setConsumptionInTown(6.5);
		car.setConsumptionOutOfTown(5);
		
		try {
			getCarDao().create(car);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
